package com.hxzy.common.util;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.hxzy.common.consts.Constants;
import com.hxzy.common.consts.RedisConstants;
import com.hxzy.controller.login.resp.AdminLoginResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService
{
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public AdminLoginResp getAdminLoginUser(HttpServletRequest request){
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StrUtil.isNotBlank(token)) {
            try
            {
                if(!JWTUtil.verify(token, this.secret.getBytes())){
                    return null;
                }

                //3、解析jwt的值  商户类型-31b8624d-7d80-4b0b-8172-5db4f9770b4d
                Object uuid = JWTUtil.parseToken(token).getPayload(Constants.LOGIN_USER_KEY);

                //4、拼接rediskey account:token:admin-a99bf377-c520-4028-ae1b-fd2f2a43347b
                String redisKey=this.getTokenKey(uuid.toString());

                Object redisValue = this.redisTemplate.opsForValue().get(redisKey);


                return Objects.isNull(redisValue)? null : (AdminLoginResp)redisValue;
            }
            catch (Exception e)
            {
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(AdminLoginResp loginUser)
    {
        if (Objects.nonNull(loginUser) && StrUtil.isNotBlank(loginUser.getToken()))  {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token)
    {
        if (StrUtil.isNotBlank(token)) {
            String userKey = getTokenKey(token);
             this.redisTemplate.delete(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(AdminLoginResp loginUser)
    {
        String token = IdUtil.fastUUID();
        loginUser.setToken(token);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);


        return  JWTUtil.createToken(claims,this.secret.getBytes());
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(AdminLoginResp loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN){
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(AdminLoginResp loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String redisKey= this.getTokenKey(loginUser.getToken());

        this.redisTemplate.opsForValue().set(redisKey, loginUser, expireTime,TimeUnit.MINUTES);
    }





    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StrUtil.isNotBlank(token) && token.startsWith("Bear"))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid)
    {
        return RedisConstants.ACCOUNT_TOKEN_PREFIX+ uuid;
    }
}
